package lockforredis.controller;

import lockforredis.common.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 测试redis分布式锁controller
 *
 * @author: 顾志杰
 */

@RestController
@Slf4j
public class RedisLockController {


    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @RequestMapping("redisLock")
    public String redisLock(){
        log.info("我进入了方法！");
        try (RedisLock redisLock = new RedisLock(redisTemplate,"redisKey",30)){

            if (redisLock.getLock()) {
                log.info("我进入了锁！！");
                Thread.sleep(15000);
            }else {
                log.info("我没抢到锁！！！");

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("方法执行完成");
        return "方法执行完成";
    }

    @RequestMapping("redisLock2")
    public String redisLock2() throws Exception{
        //利用redis的setnx原理做分布式锁  setnx：如果key存在就不能设置第二个只有第一个释放掉才可以设置第二个
        //锁key
        String lock = "redis-lock";
        //锁值 无所谓 只要不为空就行
        String lockValue = "lock-value";
        //过期时间
        long timeOut = 60L;
        Boolean ifLock = redisTemplate.opsForValue().setIfAbsent(lock, lockValue,timeOut, TimeUnit.SECONDS);
        if(ifLock){
            log.info("我进入了锁！！");
            try {
                log.info("执行业务！！");
                Thread.sleep(500);
            }  finally {
                redisTemplate.delete(lock);
            }


        }else{
            log.info("我没抢到锁！！！");
            Thread.sleep(50);
            this.redisLock2();
        }

        return "方法执行完成";
    }
}
